package com.tianpengtech.front.mobile.passport;


import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.fairauth.FairAuth;
import com.tianpengtech.common.model.fairext.FairExt;
import com.tianpengtech.common.model.fairwithdraw.FairWithdraw;
import com.tianpengtech.common.model.moneylog.MoneyLog;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.front.mobile.bankno.MobileBanknoService;
import com.tianpengtech.front.mobile.common.util.R;
import com.tianpengtech.front.mobile.common.util.TokenUtil;
import com.tianpengtech.front.mobile.common.util.U;
import com.tianpengtech.front.web.fair.FairService;

import java.util.*;

/**
 * Created by ggd on 2017/7/24 0024.
 */
public class MobilePassportService {
    public static MobilePassportService me = new MobilePassportService();
    private static FairExt fairExtDao = FairExt.dao;
    private static FairService fairService = new FairService();
    private static FairService fs = new FairService();
    private static FairAuth authDao= FairAuth.dao;
    private static final String TRAN_PWD_CACHE_KEY="tranPwd_";
    private static MobileBanknoService mbs = MobileBanknoService.me;
    /**
     * 保存网红信息
     * @param param
     * @return
     */
    public R saveOrUpdate(Map<String,String> param) throws Exception{
        try{
            //获取荣誉信息
            String honner= param.get("honners");
            //获取兴趣爱好
            String xqah=  param.get("xqah");
            //获取擅长领域
            String scly=  param.get("scly");

            String photo =  param.get("photo");
            String nickName =  param.get("nick_name");
            String gender =  param.get("gender");
            String age =  param.get("age");
            String province =  param.get("province");
            String city =  param.get("city");
            Set<String> ext_set = new HashSet<>();
            //保存荣誉信息
            if (StrKit.notBlank(honner)){
                String[] honners=honner.split(",");
                for (String h: honners) {
                    h=h.trim();
                    Ret ret = isExtExist(h,FairExt.TYPE_HONNER);
                    if (ret.isOk()){
                        ext_set.add(ret.getInt(FairExt.ID)+"");
                        continue;
                    }
                    FairExt ext=new FairExt();
                    ext.set(FairExt.ISSYSTEM,FairExt.ISSYSTEM_NO);
                    ext.set(FairExt.NAME,h);
                    ext.set(FairExt.TYPE,FairExt.TYPE_HONNER);
                    ext.save();
                    ext_set.add(ext.getInt(FairExt.ID)+"");
                }
            }
            //保存兴趣爱好
            if (StrKit.notBlank(xqah)){
                String[] xqahs=xqah.split(",");
                for (String h: xqahs) {
                    h=h.trim();
                    if (U.isInteger(h)){
                        ext_set.add(h);
                        continue;
                    }
                    Ret ret = isExtExist(h,FairExt.TYPE_XQAH);
                    if (ret.isOk()){
                        ext_set.add(ret.getInt(FairExt.ID)+"");
                        continue;
                    }
                    FairExt ext=new FairExt();
                    ext.set(FairExt.ISSYSTEM,FairExt.ISSYSTEM_NO);
                    ext.set(FairExt.NAME,h);
                    ext.set(FairExt.TYPE,FairExt.TYPE_XQAH);
                    ext.save();
                    ext_set.add(ext.getInt(FairExt.ID)+"");
                }
            }
            //保存擅长领域
            if (StrKit.notBlank(scly)){
                String[] sclys=scly.split(",");
                for (String h: sclys) {
                    h=h.trim();
                    if (U.isInteger(h)){
                        ext_set.add(h);
                        continue;
                    }
                    Ret ret = isExtExist(h,FairExt.TYPE_SCLY);
                    if (ret.isOk()){
                        ext_set.add(ret.getInt(FairExt.ID)+"");
                        continue;
                    }
                    FairExt ext=new FairExt();
                    ext.set(FairExt.ISSYSTEM,FairExt.ISSYSTEM_NO);
                    ext.set(FairExt.NAME,h);
                    ext.set(FairExt.TYPE,FairExt.TYPE_SCLY);
                    ext.save();
                    ext_set.add(ext.getInt(FairExt.ID)+"");
                }
            }

            Fair fair = new Fair();
            if (StrKit.notBlank(photo)){
                fair.set(Fair.PHOTO,photo);
            }
            if (StrKit.notBlank(nickName)){
                fair.set(Fair.NICK_NAME,nickName);
            }
            if (StrKit.notBlank(gender)){
                fair.set(Fair.GENDER,gender);
            }
            if (StrKit.notBlank(age)){
                fair.set(Fair.AGE,age);
            }
            if (StrKit.notBlank(province)){
                fair.set(Fair.PROVINCE,province);
            }
            if (StrKit.notBlank(city)){
                fair.set(Fair.CITY,city);
            }



            String id = param.get("id");
            if (StrKit.notBlank(id)){
                fair.set(Fair.ID,id);
                fair.update();
            }else{
                fair.set(Fair.ID,param.get("uid"));
                fair.save();
                id=fair.getLong(Fair.ID)+"";
            }
            if (ext_set.size()>0){
                Db.update("delete from fair_wh_ext_join where wh_id=? ",id);
            }
            //保存关联属性
            final String wh_id=id;
            ext_set.forEach( ext ->{
                Record record = new Record();
                record.set("wh_id",wh_id);
                record.set("ext_id",ext);
                Db.save("fair_wh_ext_join",record);
            });
            CacheKit.remove(FairExt.CACHE_NAME,"static_"+FairExt.TYPE_HONNER+"_"+wh_id);
            CacheKit.remove(FairExt.CACHE_NAME,"static_"+FairExt.TYPE_XQAH+"_"+wh_id);
            CacheKit.remove(FairExt.CACHE_NAME,"static_"+FairExt.TYPE_SCLY+"_"+wh_id);
            return R.ok("成功");
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * 获取详情
     * @param fairId
     * @return
     */
    public R getFairInfo(String fairId){
        Fair fair = fairService.findById(Integer.parseInt(fairId));
        if (fair==null){
            R r=R.ok("用户不存在");
            r.p("fair","");
            return r;
        }
        fair.remove(Fair.DELETETAG);
        fair.remove(Fair.ID_CARD);
        String tran=fair.get(Fair.TRAN_PWD);
        fair.remove(Fair.TRAN_PWD);
        fair.put(Fair.TRAN_PWD,tran==null?"0":"1"); //交易密码 0 未设置 1已设置
        fair.put("xqah",fair.getExt(FairExt.TYPE_XQAH));
        fair.put("scly",fair.getExt(FairExt.TYPE_SCLY));
        fair.put("honner",fair.getExt(FairExt.TYPE_HONNER));
        R r = R.ok("成功");
        r.p("fair",fair);
        return r;
    }


    /**
     * 获取系统兴趣爱好
     * @return
     */
    public R getXQAH(){
        String sql = String.format("select %s,%s from %s where %s=? and %s=?",FairExt.ID,FairExt.NAME,fairExtDao.tableName(),FairExt.ISSYSTEM,FairExt.TYPE);
        List<FairExt> list=fairExtDao.findByCache(FairExt.CACHE_NAME,"static_xqah",sql,FairExt.ISSYSTEM_YES,FairExt.TYPE_XQAH);
        R r = R.ok("成功");
        r.p("list",list);
        return r;
    }

    /**
     * 获取系统擅长领域
     * @return
     */
    public R getSCLY(){
        String sql = String.format("select %s,%s from %s where %s=? and %s=?",FairExt.ID,FairExt.NAME,fairExtDao.tableName(),FairExt.ISSYSTEM,FairExt.TYPE);
        List<FairExt> list=fairExtDao.findByCache(FairExt.CACHE_NAME,"static_scly",sql,FairExt.ISSYSTEM_YES,FairExt.TYPE_SCLY);
        R r = R.ok("成功");
        r.p("list",list);
        return r;
    }

    /**
     * 判断自定义属性是否存在
     * @param name
     * @param type
     * @return
     */
    private Ret isExtExist(String name, int type){
        String sql=String.format("select id from %s where %s=? and %s=? and %s=?",fairExtDao.tableName(),FairExt.TYPE,FairExt.ISSYSTEM,FairExt.NAME);
        FairExt ext=fairExtDao.findFirstByCache(FairExt.CACHE_NAME,"static_"+type+"_"+name,sql,type,FairExt.ISSYSTEM_NO,name);
        if (ext==null){
            return Ret.fail();
        }else{
            Ret r=Ret.ok();
            r.put("id",ext.getInt(FairExt.ID));
            return r;
        }
    }

    /**
     * 设置交易密码
     * @return
     */
    public R setTranPwd(long uid,String old_pwd,String new_pwd){
        Fair fair=fs.findById(Integer.parseInt(uid+""));
        User user = User.dao.findById(uid);
        //如果旧密码为空则是设置交易密码
        String tranPwd=fair.get(Fair.TRAN_PWD);
        if (StrKit.isBlank(tranPwd)){
            String salt = user.get(User.SALT);
            String hashedPass = HashKit.sha256(salt + new_pwd);
            fair.set(Fair.TRAN_PWD,hashedPass);
            fair.update();
            CacheKit.remove(Fair.FAIR_CACHE_NAME,"fair_info_"+uid);
            return R.ok();
        }else{
            if (StrKit.isBlank(old_pwd)){
                return R.fail("旧密码不能为空");
            }else{
                String salt = user.get(User.SALT);
                String hashedPass = HashKit.sha256(salt + old_pwd);
                if (tranPwd.toUpperCase().equals(hashedPass.toUpperCase())){
                    String hashedPass_new = HashKit.sha256(salt + new_pwd);
                    fair.set(Fair.TRAN_PWD,hashedPass_new);
                    fair.update();
                    CacheKit.remove(Fair.FAIR_CACHE_NAME,"fair_info_"+uid);
                    return R.ok();
                }else{
                    return R.fail("旧密码不正确");
                }
            }
        }
    }

    /**
     * 验证旧交易密码是否正确
     * @param uid
     * @param old_pwd
     * @return
     */
    public R checkTranPwd(long uid,String old_pwd){
        Fair fair=fs.findById(Integer.parseInt(uid+""));
        User user = User.dao.findById(uid);
        String tranPwd=fair.get(Fair.TRAN_PWD);
        String salt = user.get(User.SALT);
        String hashedPass = HashKit.sha256(salt + old_pwd);
        if (tranPwd.toUpperCase().equals(hashedPass.toUpperCase())){
            return R.ok("密码正确");
        }else{
            return R.fail("密码错误");
        }
    }

    /**
     * 保存认证信息
     * @param param
     * @return
     */
    public R saveAuth(Map<String,String> param){
        String username=param.get("user_name");
        String nickName=param.get("nick_name");
        String fans=param.get("fans");
        String screen=param.get("screenshot");
        String type=param.get("type");
        String uid=param.get("uid");
        FairAuth fa = new FairAuth();
        fa.set(FairAuth.USER_NAME,username);
        fa.set(FairAuth.NICK_NAME,nickName);
        fa.set(FairAuth.FANS,fans);
        fa.set(FairAuth.SCREENSHOT,screen);
        fa.set(FairAuth.TYPE,type);
        fa.set(FairAuth.STATUS,FairAuth.STATUS_APPROVING);
        fa.set(FairAuth.WH_ID,uid);
        fa.save();
        return R.ok();
    }

    /**
     * 获取认证信息列表
     * @param uid
     * @return
     */
    public R findAuth(long uid){
        String sql = String.format("select * from %s where %s=? and %s=?",authDao.tableName(),FairAuth.DELETETAG,FairAuth.WH_ID);
        List<FairAuth> list=authDao.find(sql,0,uid);
        list.forEach( fa ->{
            fa.remove(FairAuth.DELETETAG);
            fa.remove(FairAuth.WH_ID);
        });
        R r=R.ok();
        r.p("auths",list);
        return r;
    }


    /**
     * 获取点击数详情
     * @return
     */
    public R getClickInfo(long id){
        List<TaskWh> order=TaskWh.dao.findByCache(TaskWh.CACHE_NAME_NO,"cache_taskwh_click_no","SELECT wh_id, sum(click_num) FROM "+TaskWh.dao.tableName()+" GROUP BY wh_id ORDER BY sum(click_num) desc");
        int no=0;
        for (int i = 0; i <order.size() ; i++) {
            TaskWh tw=order.get(i);
            if (tw.getInt(TaskWh.WH_ID).intValue()==id){
                no=(i+1);
                break;
            }
        }
        R r = R.ok();
        r.p("no",no);
        //获取点击详情
        List<TaskWh> taskwhs=TaskWh.dao.find("select task.`status`,task.id,task.task_title,tw.click_num from "+TaskWh.dao.tableName()+" tw LEFT JOIN "+ Task.dao.tableName()+" task  on tw.task_id=task.id where tw.deletetag=0 and tw.wh_id=?",id);
        long sum=0;
        for (TaskWh taskWh:taskwhs) {
            sum+=(taskWh.getInt("click_num"));
        }
        r.p("list",taskwhs);
        r.p("sum",sum);
        return r;
    }


    /**
     * 获取转化数详情
     * @return
     */
    public R getCvsInfo(long id){
        List<TaskWh> order=TaskWh.dao.findByCache(TaskWh.CACHE_NAME_NO,"cache_taskwh_click_no","SELECT wh_id, sum(cvs_num) FROM "+TaskWh.dao.tableName()+" GROUP BY wh_id ORDER BY sum(cvs_num) desc");
        int no=0;
        for (int i = 0; i <order.size() ; i++) {
            TaskWh tw=order.get(i);
            if (tw.getInt(TaskWh.WH_ID).intValue()==id){
                no=(i+1);
                break;
            }
        }
        R r = R.ok();
        r.p("no",no);
        //获取转化详情
        List<TaskWh> taskwhs=TaskWh.dao.find("select task.`status`,task.id,task.task_title,tw.cvs_num from "+TaskWh.dao.tableName()+" tw LEFT JOIN "+ Task.dao.tableName()+" task  on tw.task_id=task.id where tw.deletetag=0 and tw.wh_id=?",id);
        long sum=0;
        for (TaskWh taskWh:taskwhs) {
            sum+=(taskWh.getInt("cvs_num"));
        }
        r.p("list",taskwhs);
        r.p("sum",sum);
        return r;
    }

    /**
     * 个人中心
     * @param id
     * @return
     */
    public R center(long id){
        Fair fair=Fair.dao.findFirst("select * from "+Fair.dao.tableName()+" where " +Fair.DELETETAG + "=? and "+Fair.ID+"=?",0,id);
        if (fair==null){
            return R.fail("用户不存在");
        }
        R r=R.ok();
        r.p("status",fair.get(Fair.STATUS));
        r.p("click",fair.getClick());
        r.p("cvs",fair.getCvs());
        return r;
    }

    /**
     * 我的钱包
     * @return
     */
    public R getWallet(long id){
        //获取可用余额    昨日收益 总收益
        Fair fair=Fair.dao.findFirst("select * from "+Fair.dao.tableName()+" where " +Fair.DELETETAG + "=? and "+Fair.ID+"=?",0,id);
        if (fair==null){
            return R.fail("用户不存在");
        }
        R r=R.ok();
        r.p("money",fair.get(Fair.MONEY));
        MoneyLog log=MoneyLog.dao.findFirst("select SUM(money) as money from "+MoneyLog.dao.tableName()+" where DATE_FORMAT(create_time, '%Y%m%d')=DATE_FORMAT(?, '%Y%m%d') and wh_id=?",getYesterDay(),id);
        if (log==null){
            r.p("yesterday",0);
        }else{
            r.p("yesterday",log.get("money"));
        }
        MoneyLog sumlog=MoneyLog.dao.findFirst("select SUM(money) as money from "+MoneyLog.dao.tableName()+" where wh_id=?",id);
        if (log==null){
            r.p("all",0);
        }else{
            r.p("all",sumlog.get("money"));
        }
        return r;
    }

    /**
     * 获取昨天
     * @return
     */
    private Date getYesterDay(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        Date time=cal.getTime();
        return time;
    }

    /**
     * 验证交易密码
     * @param tranPwd
     * @param uid
     * @return
     */
    public R checkTranPwd(String tranPwd,long uid){
        Fair fair=fs.findById(Integer.parseInt(uid+""));
        User user = User.dao.findById(uid);
        String nowtranPwd=fair.get(Fair.TRAN_PWD); //数据库中的交易密码
        String salt = user.get(User.SALT);
        String hashedPass = HashKit.sha256(salt + tranPwd); //传入的交易密码加密
        if (nowtranPwd.toUpperCase().equals(hashedPass.toUpperCase())){
            R r=R.ok("密码验证成功");
            String token = TokenUtil.getToken(); //在提交提现请求时 需携带此token
            CacheKit.put(User.AUTH_CODE_CACHENAME,TRAN_PWD_CACHE_KEY+uid,token); //缓存时间5分钟
            r.p("token", token);
            return r;
        }else{
            return R.fail("交易密码不正确");
        }
    }

    /**
     * 提现请求
     * @return
     */
    public R withdraw(String money,long uid,String token,String bankId){
        if (!mbs.isBankNoExists(bankId)){
            return R.fail("银行卡不存在");
        }
        Fair fair=fs.findById(Integer.parseInt(uid+""));
        Double yue=fair.getDouble(Fair.MONEY); //余额
        double tixian=Double.parseDouble(money); //提现金额
        if (yue ==null || tixian>yue.doubleValue()){
            return R.fail("提现金额超出可用余额");
        }
        String cacheToken=CacheKit.get(User.AUTH_CODE_CACHENAME,TRAN_PWD_CACHE_KEY+uid);
        if (token.equals(cacheToken)){
            CacheKit.remove(User.AUTH_CODE_CACHENAME,TRAN_PWD_CACHE_KEY+uid);
            fair.set(Fair.MONEY,yue.doubleValue()-tixian);
            if(fair.update()){
                FairWithdraw fw = new FairWithdraw();
                fw.set(FairWithdraw.BANK_ID,bankId);
                fw.set(FairWithdraw.MONEY,tixian);
                fw.set(FairWithdraw.WH_ID,uid);
                if (fw.save()){
                    MoneyLog ml = new MoneyLog();
                    ml.set(MoneyLog.WH_ID,uid);
                    ml.set(MoneyLog.OPERID,fw.get(FairWithdraw.ID));
                    ml.set(MoneyLog.STATE, MoneyLog.STATE_REDUCE);
                    ml.set(MoneyLog.TYPE,MoneyLog.TYPE_TIXIAN);
                    ml.set(MoneyLog.MONEY,tixian);
                    ml.set(MoneyLog.DESCRIPTION,"用户提现，金额："+tixian);
                    ml.save();
                    return R.ok();
                }else {
                    return R.fail("提现失败");
                }
            }else{
                return R.fail("提现失败");
            }

        }else {
            return R.fail("token不正确");
        }

    }
}
